package com.haiyi.software.app.basic;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import android.os.AsyncTask;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.haiyi.software.app.MainApplication;
import com.haiyi.software.app.R;
import com.haiyi.software.entity.UserInfo;

public abstract class FragmentBasicVPFriends extends FragmentBasic {

	private List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();

	public List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();

	protected String str_server = null;

	public String str_requestURL = null;

	// 默认头像
	public String str_defaultPhoto = null;

	private String str_requestName = "";

	protected String getStr_requestName() {
		return str_requestName;
	}

	/**
	 * 设置请求的地址
	 * 
	 * @param str_requestName
	 */
	protected void setStr_requestName(String str_requestName) {
		this.str_requestName = str_requestName;
	}

	private Boolean isWork = false;

	public Boolean getIsWork() {

		return isWork;
	}

	@Override
	public synchronized void requestNetworkData() {

		str_server = this.getResources().getString(R.string.URL);
		str_requestURL = this.getResources().getString(R.string.URL);
		str_defaultPhoto = this.getResources().getString(R.string.DefaultPhoto);
		str_requestURL = str_requestURL + str_requestName;
		new GetDataTask().execute();
		// }
	}

	private class GetDataTask extends
			AsyncTask<Void, Void, List<Map<String, Object>>> {

		@Override
		protected List<Map<String, Object>> doInBackground(Void... params) {

			// httpPost连接对象
			HttpPost httpPost = new HttpPost(str_requestURL);
			// 使用NameValuePair来保存要传递的post阐述
			List<NameValuePair> params1 = new ArrayList<NameValuePair>();
			// 添加要传递的参数
			params1.add(new BasicNameValuePair("args", getJsonArgs()));
			try {
				// 设置字符集
				HttpEntity httpEntity = new UrlEncodedFormEntity(params1,
						"utf-8");
				httpPost.setEntity(httpEntity);
				// 取得默认的HttpClient
				HttpClient httpClient = new DefaultHttpClient();
				// 取得HttpResponse
				HttpResponse httpResponse = httpClient.execute(httpPost);
				// HttpStatus.SC_OK)表示连接成功
				if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {

					list.clear();

					// 取得返回的字符串
					String result = EntityUtils.toString(httpResponse
							.getEntity());

					Log.i("res", result);

					Gson gson = new Gson();

					JsonParser parser = new JsonParser();

					JsonObject jsonResult = parser.parse(result)
							.getAsJsonObject();

					Log.i("jsonResult", jsonResult == null ? "null"
							: "not null");

					Log.i("state", jsonResult.get("state").getAsString());

					if (jsonResult.get("state").getAsString().equals("200")) {

						JsonArray personlist = jsonResult.getAsJsonObject(
								"body").getAsJsonArray("personlist");

						Type type = new TypeToken<Map<String, String>>() {
						}.getType();

						for (int i = 0; i < personlist.size(); i++) {
							JsonElement el = personlist.get(i);

							Map<String, Object> tmp = gson.fromJson(el, type);
							list.add(tmp);
						}
					} else {
						Log.i("getFriends", "没有好友");
					}

				} else {
					Log.i("network", "网络连接失败");
				}
			} catch (ClientProtocolException e) {
				Log.e("PostActivity", "ClientProtocolException");
				e.printStackTrace();
			} catch (IOException e) {
				Log.e("PostActivity", "IOException");
				e.printStackTrace();
			} catch (Exception e) {
				// TODO: handle exception
				Log.e("PostActivity", "Exception");
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(List<Map<String, Object>> result) {

			data.clear();
			data.addAll(list);
			super.onPostExecute(result);
			requestFinish();
		}
	}

	private String getJsonArgs() {

		UserInfo myInfo = MainApplication.getInstance().getMineUserInfo();

		if (myInfo != null) {

			Map<String, Object> validator = new HashMap<String, Object>();

			validator.put("uid", myInfo.getUid());
			validator.put("uname", myInfo.getUname());
			validator.put("pwd", myInfo.getPwd());
			validator.put("uguid", myInfo.getUguid());

			Map<String, Object> body = new HashMap<String, Object>();
			body.put("lat", myInfo.getLat());
			body.put("longitude", myInfo.getLongitude());
			// TODO:以后要做分页
			body.put("page", 1);
			body.put("percount", 99999);

			Map<String, Object> args = new HashMap<String, Object>();
			args.put("validator", validator);
			args.put("body", body);

			Gson gson = new Gson();
			String s = gson.toJson(args);

			Log.i("argsJson", s);
			return s;
		} else {
			return "";
		}

	}

}
